package com.fezs.message.template;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.fezs.message.entity.MsgEntity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhukai
 * @since 2022/8/18
 */
@Slf4j
@Getter
@Setter
@ToString
public class MessageTemplate {

    private final String WX_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";

    /**
     * key
     */
    private String key;

    /**
     * 代理
     */
    private String proxyHost;

    /**
     * 代理端口
     */
    private Integer proxyPort;

    /**
     * 发送消息
     */
    public void send(MsgEntity msgEntity) {
        HttpRequest post = HttpUtil.createPost(WX_URL + key).body(JSONUtil.toJsonStr(msgEntity));
        if (StrUtil.isNotEmpty(proxyHost) && proxyPort != null) {
            post.setHttpProxy(proxyHost, proxyPort);
        }
        String response = post.execute().body();
        log.info("发送消息返回响应:{}", response);
    }

    public static MessageTemplate buildMessageTemplate(String key) {
        return buildMessageTemplate(key, null, null);
    }

    public static MessageTemplate buildMessageTemplate(String key, String proxyHost, Integer proxyPort) {
        MessageTemplate template = new MessageTemplate();
        template.setKey(key);
        template.setProxyHost(proxyHost);
        template.setProxyPort(proxyPort);
        return template;
    }

}
